var mdLiveLastValue = ''
var mdLiveLastTime = ''
function onLiveInputChange() {
    var t = document.getElementById('md-live-input-area')
    var r = document.getElementById('md-live-output-area')
    var i = document.getElementById('article-id')
    var mdLiveNowTime = new Date().toString()
    var mdLiveNewValue = t.value
    var diff = JsDiff.createPatch("md-live-diff", mdLiveLastValue, t.value, mdLiveLastTime, mdLiveNowTime)
    var shouldUpdateMathJax = false
    if (diff.match('') != null) {
        shouldUpdateMathJax = true
    }else{
        shouldUpdateMathJax = false
    }
    mdLiveLastTime = mdLiveNowTime
    mdLiveLastValue = mdLiveNewValue
    
    $.ajax({
            type: "POST",     //提交方式
            contentType: "application/json; charset=utf-8",   //内容类型
            dataType: "json",     //类型
            url: "/ajax/mdLive/update",    //提交的页面，方法名
            data: JSON.stringify({update: base64encode(diff), id: base64encode(i.value)}),    //参数，如果没有，可以为null
            success: function (data) { //如果执行成功，那么执行此方法
                r.innerHTML = data.res
                shouldUpdateMathJax ? window.MathJax.Hub.Typeset() : nil;
            },
            error: function (err) { //如果执行不成功，那么执行此方法
            }
    });

}

function onSaveButtonDown() {
    var i = document.getElementById('article-id')
    var t = document.getElementById('md-live-input-area')
    var articleMdText = t.value
    
    console.log(articleMdText)
        $.ajax({
            type: "POST",     //提交方式
            contentType: "application/json; charset=utf-8",   //内容类型
            dataType: "json",     //类型
            url: "/ajax/mdLive/saveArticle",    //提交的页面，方法名
            data: JSON.stringify({text: window.btoa(window.encodeURIComponent(articleMdText)), id: window.btoa(window.encodeURIComponent(i.value))}),    //参数，如果没有，可以为null
            success: function (data) { //如果执行成功，那么执行此方法
                alert('保存' + data.return)
                console.log('保存成功')
                location.reload()
            },
            error: function (err) { //如果执行不成功，那么执行此方法
                alert(err.responseText)
            }
    });
}